﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using IoTEdge.Grpc.Server.ABBLibs.Base;
using NLog;
using System.ServiceProcess;
namespace IoTEdge.Grpc.Server
{
    public class BackgroundABBCollectPlugin : BackgroundService
    {
        Logger logger = LogManager.GetCurrentClassLogger();
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            var task2 = Task.Factory.StartNew(x =>
            {
                var cancel = (CancellationToken)x;
                logger.Info("ABB采集驱动正在运行!");
                ABBCollect abbCollect = new ABBCollect();
                try
                {
                    abbCollect.Start(cancel, RestartABB);
                }
                catch (Exception exp)
                {
                    logger.Fatal($"ABB采集驱动出现致命错误: {exp.Message}");
                    return;
                }
            }, stoppingToken);
            await Task.WhenAll(task2);
        }
        public void RestartABB()
        {
            ABBCollect collect = new ABBCollect();
            logger.Warn("ABB采集驱动正在重新启动!...");
            collect.Start(CancellationToken.None, RestartABB);

        }
        public override async Task StopAsync(CancellationToken cancellationToken)
        {
            await base.StopAsync(cancellationToken);
        }
    }
}
